package io.gitee.zhangbinhub.acp.core.file.pdf

import com.itextpdf.text.Document
import com.itextpdf.text.ExceptionConverter
import com.itextpdf.text.pdf.BaseFont
import com.itextpdf.text.pdf.PdfPageEventHelper
import com.itextpdf.text.pdf.PdfTemplate
import com.itextpdf.text.pdf.PdfWriter
import io.gitee.zhangbinhub.acp.core.file.pdf.fonts.FontLoader

class PageNumberHandle(private val baseFont: BaseFont?) : PdfPageEventHelper() {
    private val fontSize = 8f
    private val currNumX = 450f
    private val currNumY = 20f
    private val totalNumX = 497f
    private val totalNumY = 20f

    /**
     * 当前页码字符串，变量名“pageNumber”
     */
    private val currNumStr = "第 [pageNumber] 页 / 共 "

    /**
     * 总页数字符串，变量名“pageTotal”
     */
    private val totalNumStr = "[pageTotal] 页"

    /**
     * 字体
     */
    private var tpl: PdfTemplate? = null
    override fun onOpenDocument(writer: PdfWriter, document: Document) {
        tpl = try {
            writer.directContent.createTemplate(100f, 100f)
        } catch (e: Exception) {
            throw ExceptionConverter(e)
        }
    }

    override fun onEndPage(writer: PdfWriter, document: Document) {
        val currNumLen = writer.pageNumber.toString().length
        val cb = writer.directContent
        cb.saveState()
        val text = currNumStr.replace("[pageNumber]", writer.pageNumber.toString())
        cb.beginText()
        cb.setFontAndSize(baseFont, fontSize)
        cb.setTextMatrix(currNumX, currNumY)
        cb.showText(text)
        cb.endText()
        cb.addTemplate(tpl, totalNumX + currNumLen * 5, totalNumY)
        cb.stroke()
        cb.restoreState()
        cb.closePath()
    }

    override fun onCloseDocument(writer: PdfWriter, document: Document) {
        tpl!!.beginText()
        tpl!!.setFontAndSize(baseFont, fontSize)
        tpl!!.showText(totalNumStr.replace("[pageTotal]", (writer.pageNumber - 1).toString()))
        tpl!!.endText()
        tpl!!.closePath()
    }
}
